home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 9360 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.9 KB

  1. Path: lrz-muenchen.de!news
  2. From: watzka@stat.uni-muenchen.de (Kurt Watzka)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Q: How to assign structures?
  5. Date: 9 Mar 1996 19:45:52 GMT
  6. Organization: Leibniz-Rechenzentrum, Muenchen (Germany)
  7. Distribution: world
  8. Message-ID: <4hsn5g$44s@sparcserver.lrz-muenchen.de>
  9. References: <4gsalu$dll@ccshst05.cs.uoguelph.ca> <4hse0f$efq@SNFC21_SRVR_WWW.PBI.net>
  10. NNTP-Posting-Host: sun2.lrz-muenchen.de
  11.  
  12. mich@pbinet.com writes:
  13.  
  14. >In <4gsalu$dll@ccshst05.cs.uoguelph.ca>, thay@uoguelph.ca (Toby K Hay) writes:
  15. >>I need to assign values to structures in one array from structures in 
  16. >>another array - in essence I'm copying the whole structure from one array 
  17. >>to the other.  Can I use simple assignment like this:
  18.  
  19. >>struct StructName {
  20. >>    int     IVal;
  21. >>    float    FVal;}
  22.  
  23. >>struct StructName Array1[5], Array2[5];
  24. >>.. . .
  25. >>for (i=0;i<5;i++) Array1[i] = Array2[i];
  26. >>.. . .
  27. >>And if not that, can I use memcpy() and sizeof() to do the assignment:
  28.  
  29. >>for (i=0;i<5;i++) memcpy(&Array2[i],&Array1[i],sizeof(struct StructName));
  30. >>Or do I have to assign each element of the structure?
  31.  
  32. >It would be a lot easier to create a pointer to the struct and then make a copy
  33. >of the pointer;
  34.  
  35. I beg to differ. Copying pointers is _not_ equivalent to copying values.
  36. Consider an algorithm that will change the contents of the array
  37. of structures. Since you want to _keep_ the original values as well,
  38. what would you do using your approach?
  39.  
  40. It _may_ be useful to pass a pointer to a struct to a function instead
  41. of the whole struct, but sometimes you just _need_ the call by value
  42. semantics that C uses in all function calls. 
  43.  
  44. >struct mystruct {..} ms, *ps;
  45.  
  46. >main()
  47. >{
  48. >    void *ns;
  49.  
  50. Why on earth do we need a void * in this program. 
  51.  
  52. >    ps = &ms;
  53. >    ns = ps;
  54. >}
  55.  
  56. Kurt
  57. --
  58. | Kurt Watzka                             Phone : +49-89-2180-6254
  59. | watzka@stat.uni-muenchen.de
  60. | ua302aa@sunmail.lrz-muenchen.de
  61.